
import { Control_Listen, Login_Status, UI_Layer } from "../constants/ui_def";
import { gg } from "../frame/gg";
import { he } from "../frame/he";
import { common } from "./common";

const { ccclass, property } = cc._decorator;

@ccclass
export default class Login extends cc.Component {
    @property(cc.Label)
    version_label: cc.Label = null
    @property(cc.Prefab)
    manager_prefab: cc.Prefab = null  // 常驻预制体
    @property(cc.Node)
    login_bg_node: cc.Node = null     // 整体背景图片
    @property(cc.Node)
    logo_node: cc.Node = null         // Logo节点
    bundle_list: string[] = []             // 包加载状态list
    res_list: string[] = []               // 资源加载状态list
    @property(cc.Node)
    loading_node: cc.Node = null      // 加载节点
    @property(cc.Node)
    restart_login_node: cc.Node = null// 重新更新节点
    @property(cc.Node)
    loading_label: cc.Label = null    // 加载LoadingLabel
    @property(cc.Node)
    loading_bar_sprite: cc.Sprite = null      //  

    check_load: boolean = false
    tip_time: number = 0
    // onLoad () {}
    // 加载顺序 
    // 加载Bundle包 -》 播放主题曲 -》 初始化SDK-》 加载用户数据 -》 加载数据 -》 加载资源包 -》 启动游戏
    start() {
        // console.log(he.Load)
        // let dic = {}
        // he.Local.setJson('user', { name: 'linyi' }, null)
        // console.log(he.Local.getJson('user', null))

        // 屏幕自适应
        // this.adjust_screen()
        // 初始化音乐
        // 初始化管理内容
        let currentScene = cc.director.getScene()
        let manager_node = currentScene.getChildByName("manager")
        // 检测 管理节点是否存在
        this.restart_login_node.active = false
        let isHave = false
        for (let i = 0; i < currentScene.children.length; i++) {
            if (currentScene.children[i].name == 'manager') {
                isHave = true
            }
        }
        if (!isHave) {
            // let eventManager = new cc.EventTarget()
            let managerPrefab = cc.instantiate(this.manager_prefab)
            currentScene.addChild(managerPrefab)
            let managerScript = managerPrefab.getComponent("manager")
            managerScript.start_app()
            cc.director.on("login", this.listenClient, this)
        }
        he.Voice.checkSetting()
        // sdk 检测
        this.bundle_list = []
        if (common.bundle_list && common.bundle_list.length) {
            for (let i = 0; i < common.bundle_list.length; i++) {
                he.Load.loadBundle(common.bundle_list[i], this.checkBundle.bind(this), null)
            }
        } else {
            he.sdkInit()
        }
    }

    checkBundle(error, res) {
        if (res && res.name) {
            this.bundle_list.push(res.name)
            if (common.bundle_list.length == this.bundle_list.length) {
                he.sdkInit()
            }
        }
    }
    // 按宽窄来进行自适应
    adjust_screen() {
        let screen_size = cc.view.getFrameSize().width / cc.view.getFrameSize().height
        let design_size = cc.Canvas.instance.designResolution.width / cc.Canvas.instance.designResolution.height

        // 比例调整
        common.zoom_scale = screen_size / design_size
        let f = screen_size >= design_size
        cc.Canvas.instance.fitHeight = f
        cc.Canvas.instance.fitWidth = !f
        if (common.zoom_scale > 1.3) {
            common.zoom_scale = 1
        }
        // Logo和背景缩放
        // this.login_bg_node.scale = common.zoom_scale
        // this.logo_node.scale = common.zoom_scale
    }
    // 加载本地资源
    loadResources() {
        this.loading_node.active = true
        if (common.UI_Init.length) {
            he.Load.loadResList(common.UI_Init, this.updateLoadbar.bind(this))
        } else {
            this.toMain()
        }
    }
    // 更新进度条
    updateLoadbar(err, res) {
        if (this.res_list.indexOf(res.name) < 0) {
            this.res_list.push(res.name)
        }
        this.loading_bar_sprite.fillRange = this.res_list.length / common.UI_Init.length
        // 标签显示
        if (this.version_label) {
            this.version_label.node.active = true
            this.version_label.string = `当前版本：` + common.version
            // this.version_widget.updateAlignment()
            this.tip_time = 0
            // this.changeTip()
            this.loading_label.string = 100 * he.Load.loadStatus() + `%`
            // 开启版本和tip
        }
        if (this.res_list.length == common.UI_Init.length) {
            this.loginGame()
        }
    }
    // 成功载入主场景
    toMain() {
        this.check_load = true
        gg.uiManager.addPage(UI_Layer.Load, {
            name: "transition",
            url: "base/transition",
            type: Control_Listen.OPEN_TRANSITION,
            scene: "Main"
        })
    }
    // 登录游戏操作
    loginGame() {
        this.listenClient(Login_Status.LOGIN, null, null)
        he.User.login()
        this.restart_login_node.active = false
    }
    // 登录监听
    listenClient(code, param, arg) {
        console.log(code)
        if (code) {
            switch (code) {
                case Login_Status.LOGIN:
                    this.loading_label.string = `登陆中` 
                    break
                case Login_Status.LOAD_RES:
                    this.loading_label.string = `加载资源中`
                    this.loadResources()
                    break
                case Login_Status.LOGIN_FAIL:
                    this.loading_label.string = `登录失败，请重新登录`
                    this.restart_login_node.active = true
                    break
                case Login_Status.LOGIN_SUCCESS:
                    this.loading_label.string = `登录成功`
                    he.switchInit()
                    break
                case Login_Status.TO_MAIN:
                    this.toMain()
                    break
                case Login_Status.CHECK_UPDATE:
                    this.loading_label.string = `资源更新中`
                    break
                case Login_Status.UPDATE_FAIL:
                    this.loading_label.string = `更新失败，重启应用`
                    break
            }
        }
    }
    onDestroy() {
        cc.director.off("login", this.listenClient, this)
    }

}
